package com.hydra.gateway.config;

import com.hydra.gateway.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 令牌无效或者过期时定制结果
 */
@Slf4j
@Component
public class RestAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException exception) {
        log.warn("token授权认证失败："+exception.getMessage());
        if(!(exception instanceof InvalidBearerTokenException)){
            log.error(exception.getMessage(), exception);
        }

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        HttpStatus httpStatus = HttpStatus.UNAUTHORIZED;

        return ResponseUtil.writeResponseMono(request, response, httpStatus, exception.getMessage());

    }
}